package product

import (
	"fmt"
	"vue-admin-server/global"
	"vue-admin-server/model/product"
	"vue-admin-server/model/product/response"
)

type TestReportService struct{}

func (trs *TestReportService) GetTestReportHistory(chipIdStr string) ([]product.TestReport, error) {
	var testReports []product.TestReport
	err := global.GVA_DB.Where("chip_id = ?", chipIdStr).Order("test_time desc").Find(&testReports).Error
	if err != nil {
		return nil, err
	}
	return testReports, nil
}

func (trs *TestReportService) GetTestReportInfo(chipIdStr, reportIdStr string) (*response.ChipTestReport, error) {
	var chipSpec product.ChipSpec
	err := global.GVA_DB.First(&chipSpec, "id = ?", chipIdStr).Error
	if err != nil {
		return nil, err
	}

	var testReport product.TestReport
	err = global.GVA_DB.First(&testReport, "id = ?", reportIdStr).Error
	if err != nil {
		return nil, err
	}

	testReportResp := &response.ChipTestReport{
		ChipID:        chipSpec.ID,
		Supplier:      chipSpec.Supplier,
		ChipNo:        chipSpec.ChipNo,
		RaycusNo:      chipSpec.RaycusNo,
		ModuleType:    testReport.ModuleType,
		Description:   testReport.Description,
		TestTime:      testReport.TestTime,
		TestContent:   testReport.TestContent,
		ReportFileURL: testReport.ReportFileURL,
		Params:        make(map[string][]response.ChipTestReportParam, 0),
	}

	sqlStr := `
SELECT 
    cpv.id AS id,
    cpv.report_id AS chip_id,
    cp.item_id AS item_id,
    cp.item AS item,
    cp.parameter_id AS parameter_id,
    cp.parameter AS parameter,
    cp.symbol AS symbol,
    cp.unit AS unit,
    cpv.test_condition AS test_condition,
    cpv.min_value AS min_value,
    cpv.max_value AS max_value,
    cpv.typical_value AS typical_value
FROM
    chip_parameter_values cpv
        LEFT JOIN
    chip_parameters cp ON cpv.item_id = cp.item_id
        AND cpv.parameter_id = cp.parameter_id
WHERE
    report_id = %v AND report_type = 'TEST'
ORDER BY id

`
	params := make([]response.ChipTestReportParam, 0)
	err = global.GVA_DB.Raw(fmt.Sprintf(sqlStr, reportIdStr)).Find(&params).Error
	if err != nil {
		return testReportResp, nil
	}

	for _, p := range params {
		if p.ItemID == "fac_coupling" {
			testReportResp.Params["fac_coupling"] = append(testReportResp.Params["fac_coupling"], p)
		} else if p.ItemID == "reflector_coupling" {
			testReportResp.Params["reflector_coupling"] = append(testReportResp.Params["reflector_coupling"], p)
		} else if p.ItemID == "series_power_test" {
			testReportResp.Params["series_power_test"] = append(testReportResp.Params["series_power_test"], p)
		} else if p.ItemID == "reliability_test" {
			testReportResp.Params["reliability_test"] = append(testReportResp.Params["reliability_test"], p)
		} else if p.ItemID == "final_test" {
			testReportResp.Params["final_test"] = append(testReportResp.Params["final_test"], p)
		}

	}
	return testReportResp, nil
}
